using System;
using System.Collections.Generic;
using System.Text;
using Exceptions;

namespace FrameIdentityReq.Frames
{
    public class BitsField : IBytesField
    {

        IBytesBuffer _Buffer;
        public IList<byte> Buffer { get { return _Buffer.Buffer; } }
        public int Index { get; }
        public int Count { get; }
        public string Name { get; }

        public BitsField(IBytesBuffer buffer, int index, int count, string name)
        {
            _Buffer = buffer;
            Index = index;
            Count = count;
            Name = name;
        }

        public BitsField(IField field, int count, string name)
            : this(field, field.Index + field.Count, count, name) { }

        public byte[] Value
        {
            get
            {
                byte[] arr = new byte[CeilingByteCount(Count)];
                BitsVariable source = new BitsVariable(Buffer, Index);
                BitsVariable target = new BitsVariable(arr, (arr.Length << 3) - Count);
                source.CopyTo(target, Count);
                return arr;
            }

            set
            {
                int indexSource = (value.Length << 3) - Count;
                BitsVariable source = new BitsVariable(value, indexSource);
                BitsVariable target = new BitsVariable(Buffer, Index);
                source.CopyTo(target, Count);
            }
        }

        public static int CeilingByteCount(int bitCount)
        {
            return (bitCount + 7) >> 3;
        }
    }
}